package com.xiaoxin.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.xiaoxin.dubbo.utils.IdWorker;
import com.xiaoxin.dubbo.utils.TimeLineService;
import com.xiaoxin.model.mongo.Movement;
import com.xiaoxin.model.mongo.MovementTimeLine;
import com.xiaoxin.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author xiaoxiaode
 * @date 2021-09-03-20:06
 **/
@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    /*
     * 发布动态
     * */
    public void publish(Movement movement) {
        try {
            // 保存动态详情
            movement.setPid(idWorker.getNextId("movement"));
            // 查询当前用户的好友数据
            movement.setCreated(System.currentTimeMillis());
            // movement.setId(ObjectId.get());
            mongoTemplate.save(movement);
            timeLineService.saveTimeLine(movement.getUserId(), movement.getId());
        } catch (Exception e) {
            // 忽略事务
            e.printStackTrace();
        }
    }

    /*
     * 查询自己的动态
     * */
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page, pagesize, 0L, movements);
    }

    /*
     * 查询当前用户好友的动态
     * */
    public List<Movement> findFriendMovement(Integer page, Integer pagesize, Long friendId) {
        List<Movement> movements = null;
            // 根据friendId查询时间线表
            Query query = Query.query(Criteria.where("friendId").is(friendId))
                    .skip((page - 1) * pagesize)
                    .limit(pagesize)
                    .with(Sort.by(Sort.Order.desc("created")));
            List<MovementTimeLine> timeLines = mongoTemplate.find(query, MovementTimeLine.class);
            // 提取动态id列表
            List<ObjectId> list = CollUtil.getFieldValues(timeLines, "movementId", ObjectId.class);
            // 根据动态id列表查询动态详情
            Query query1 = new Query();
            if (list != null) {
                query1 = Query.query(Criteria.where("id").in(list));
            }
            movements = mongoTemplate.find(query1, Movement.class);
        return movements;
    }

    @Override
    public List<Movement> findMovementByPids(List<Long> pids) {
        Query query = Query.query(Criteria.where("pid").in(pids));
        return mongoTemplate.find(query, Movement.class);
    }

    @Override
    public List<Movement> randomMovement(Integer counts) {
        // 创建统计对象
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(counts));
        // 调用mongoTemplate方法统计
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        // 获取统计结果
        return results.getMappedResults();
    }

    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(movementId, Movement.class);
    }

    @Override
    public PageResult getMessages(Long uid, Integer state, Integer page, Integer pagesize) {

        Query query=new Query();
        if(uid!=null){
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if(state!=null){
            query.addCriteria(Criteria.where("state").is(state));
        }
        long count = mongoTemplate.count(query, Movement.class);

        query.skip((page-1)*pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return  new PageResult(page,pagesize,count,movements);

    }
}